'use strict'

import {
    app,
    protocol,
    BrowserWindow,
    ipcMain,
    ipcRenderer,
    globalShortcut,
} from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import path from 'path'
const Store = require('electron-store')
Store.initRenderer()
const store = new Store()
// import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
const isDevelopment = process.env.NODE_ENV !== 'production'

// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([
    { scheme: 'app', privileges: { secure: true, standard: true } },
])
const winURL =
    process.env.NODE_ENV === 'development'
        ? 'http://127.0.0.1:8001/#/'
        : `file://${__dirname}/index.html`
const opts: WindowOpts = {
    height: 900,
    width: 1600,
    minWidth: 1024,
    minHeight: 768,
    modal: false,
    frame: false,
    useContentSize: true,
    parent: null,
    icon: path.join(__dirname, 'assets/icon.ico'),
    webPreferences: {
        // Use pluginOptions.nodeIntegration, leave this alone
        // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
        nodeIntegration: process.env
            .ELECTRON_NODE_INTEGRATION as unknown as boolean,
        contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
        webSecurity: false,
        preload: '',
    },
}
// let loading: any
// const showLoading = (cb: any) => {
//   loading = new BrowserWindow({
//       show: false,
//       frame: false, // 无边框（窗口、工具栏等），只包含网页内容
//       width: 160,
//       height: 180,
//       resizable: false,
//       transparent: true, // 窗口是否支持透明，如果想做高级效果最好为true
//   });

//   loading.once("show", cb)
//   loading.loadFile("loading.html")
//   loading.show()
// }
let win: any
const newWinData: any = {}
const subWins: any = {}
async function createWindow() {
    // Create the browser window.
    win = new BrowserWindow({ ...opts })
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL as string)
        // if (!process.env.IS_TEST) win.webContents.openDevTools()
    } else {
        createProtocol('app')
        // Load the index.html when not in development
        win.loadURL(winURL)
    }
    win.webContents.openDevTools()
    // 标题栏窗口点击事件
    ipcMain.on('control', async (event, ...args) => {
        if (args[0] === 'min') {
            win.minimize()
        } else if (args[0] === 'max') {
            if (win.isMaximized()) {
                win.unmaximize()
            } else {
                win.maximize()
            }
        } else if (args[0] === 'close') {
            // if (args[2]) {
            //   console.log('args[2]:', args[2])
            //   // await args[2]()
            // }
            // for (const key in subWins) {
            //   if (subWins[key]) {
            //     subWins[key].close()
            //   }
            // }
            // ipcMain.removeHandler('get-data')
            win.close()
        } else if (args[0] === 'new-win') {
            openAddNewWindow(args[1])
        } else if (args[0] === 'relaunch') {
            win.reload()
        }
    })
    ipcMain.on('sendData', (event, ...args) => {
        newWinData[args[0]][args[1]] = args[2]
    })
    ipcMain.handle('resourcePath', () => {
        return process.env.NODE_ENV === 'development'
            ? `${path.join(__dirname, '\\win-unpacked\\resources\\app')}`
            : path.join(__dirname, '')
    })
    ipcMain.handle('DefaultRoot', () => {
        return `.\\photlab`
        // return `${app.getPath('documents')}\\photlab`
    })
    ipcMain.on('setStore', (_, key, value) => {
        let jsonStr = typeof value === 'object' ? JSON.stringify(value) : value
        store.set(key, jsonStr)
    })
    ipcMain.on('getStore', (_, key) => {
        let value = store.get(key)
        if (typeof value === 'string') {
            try {
                var obj = JSON.parse(value)
                if (typeof obj == 'object' && obj) {
                    _.returnValue = obj || null
                } else {
                    _.returnValue = value || null
                }
            } catch (e) {
                _.returnValue = value || null
            }
        } else {
            _.returnValue = null
        }
    })
    ipcMain.on('deleteStore', (_, key) => {
        if (store.has(key)) store.delete(key)
    })
    ipcMain.on('clearStore', (_) => {
        store.clear()
    })
    ipcMain.on('setDefaultStore', (_) => {
        const defaultSetting = {
            locale: 'zh-CN',
            theme: 'light',
            savePath: `.\\photlab`,
            // "savePath": `${app.getPath('documents')}\\photlab`,
            server: {
                ip: "10.126.59.54",
                port: "6060"
                // ip: '127.0.0.1',
                // port: '9000',
            },
            backupTime: '15',
            autoSave: true,
        }
        store.set('_setting', JSON.stringify(defaultSetting))
        _.returnValue = defaultSetting
    })
    // win.once("ready-to-show", () => {
    //   loading.hide();
    //   loading.close();
    //   win.show();
    // });
}
// app.whenReady().then(() => {
//   // 注册一个'CommandOrControl+X' 快捷键监听器
//   const shortcutList = [
//     // 'CommandOrControl+C', // 复制
//     // 'CommandOrControl+X', // 剪切
//     // 'CommandOrControl+V', // 粘贴
//     'CommandOrControl+O', // 打开
//     // 'CommandOrControl+W', // 关闭
//     // 'CommandOrControl+S', // 保存
//     'CommandOrControl+N', // 创建
//     // 'CommandOrControl+A', // 全选
//     // 'Delete', // 删除
//   ]
//   shortcutList.map(item => {
//     const ret = globalShortcut.register(item, () => {
//       console.log(item + ' is pressed')
//       win.webContents.send(item)
//     })
//     if (!ret) {
//       console.log('registration failed')
//     }
//     // 检查快捷键是否注册成功
//     // console.log(globalShortcut.isRegistered(item))
//   })

// })
// Quit when all windows are closed.
app.on('window-all-closed', () => {
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') {
        app.quit()
    }
})
app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', async () => {
    //   if (isDevelopment && !process.env.IS_TEST) {
    //     // Install Vue Devtools
    //     try {
    //       await installExtension(VUEJS3_DEVTOOLS)
    //     } catch (e) {
    //       console.error('Vue Devtools failed to install:', e.toString())
    //     }
    //   }
    createWindow()
})
app.on('will-quit', () => {
    // 注销所有快捷键
    globalShortcut.unregisterAll()
})

// 根据路由路径设置不同窗口配置并新建窗口
async function openAddNewWindow(route: any) {
    const PHOT_ANALYZE = 'PhotAnalyze'
    const MATERIAL_LIBRARY = 'MaterialLibrary'
    const Add_MATERIAL = 'AddMaterial'
    newWinData[route] = {}
    let newWin: any = null
    let newOpts: any = {}
    if (route === PHOT_ANALYZE) {
        newOpts = {
            width: 1600,
            height: 900,
            minWidth: 1024,
            minHeight: 768,
            frame: false,
            icon: path.join(__dirname, 'assets/icon.ico'),
        }
    } else if (route === MATERIAL_LIBRARY) {
        newOpts = {
            width: 738,
            height: 502,
            minWidth: 738,
            minHeight: 502,
            frame: false,
            resizable: false,
            icon: path.join(__dirname, 'assets/icon.ico'),
            parent: win,
            modal: true,
            show: false,
        }
    } else if (route === Add_MATERIAL) {
        newOpts = {
            width: 262,
            height: 359,
            minWidth: 262,
            minHeight: 359,
            frame: false,
            resizable: false,
            icon: path.join(__dirname, 'assets/icon.ico'),
            parent: win,
            modal: true,
            show: false,
        }
    }
    const obj = Object.assign({ ...{}, ...opts, ...newOpts })
    // if (subWins[route]) {
    //   newWin = subWins[route]
    // } else {
    newWin = new BrowserWindow({ ...obj })
    //   subWins[route] = newWin;
    // }
    if (process.env.WEBPACK_DEV_SERVER_URL) {
        // Load the url of the dev server if in development mode
        await newWin.loadURL(process.env.WEBPACK_DEV_SERVER_URL + '#/' + route)
        // if (!process.env.IS_TEST) win.webContents.openDevTools()
    }
    newWin.webContents.openDevTools()
    newWin.once('ready-to-show', () => {
        newWin.show()
    })
    const childHandle = `child-${route}`
    newWin.on('closed', () => {
        ipcMain.removeAllListeners(childHandle)
        ipcMain.removeAllListeners('getData')
        // newWin.hide();
        newWin = null
        // subWins[route] = null;
    })
    ipcMain.on(childHandle, (event, ...args) => {
        console.log('childHandle:', childHandle, event, args)
        console.log('event:', event)
        console.log('args:', args)
        if (args[0] === 'min') {
            newWin.minimize()
        } else if (args[0] === 'max') {
            if (newWin.isMaximized()) {
                newWin.unmaximize()
            } else {
                newWin.maximize()
            }
        } else if (args[0] === 'close') {
            win.focus()
            newWin.close()
            ipcMain.removeHandler('get-data')
        } else if (args[0] === 'data') {
        }
    })
    ipcMain.handle('get-data', async (event, ...args) => {
        const result: any = await new Promise((resolve) => {
            setTimeout(() => {
                resolve(newWinData[route])
            }, 2000)
        })
        return result
    })
    ipcMain.on('child-data', (event, ...args) => {
        console.log(args)
    })
    ipcMain.on('sendMsgMain', (e, msg) => {
        console.log(newWin)
        // newWin.webContents.send('msgFromMain', msg)
    })
}

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
    if (process.platform === 'win32') {
        process.on('message', (data) => {
            if (data === 'graceful-exit') {
                app.quit()
            }
        })
    } else {
        process.on('SIGTERM', () => {
            app.quit()
        })
    }
}
